"""
传感器监测系统主程序
Main program for sensor monitoring system
Version 2.2: Add Modbus sensor support, removed backup functionality
"""

import time
import logging
import signal
import sys
from modules.sensor_handler import SensorHandler
from modules.data_manager import DataManager
from modules.server_client import ServerClient
from config import LOG_CONFIG, SENSOR_CONFIG

# 配置日志
logging.basicConfig(
    level=getattr(logging, LOG_CONFIG['level']),
    format=LOG_CONFIG['format'],
    handlers=[
        logging.FileHandler(LOG_CONFIG['file'], encoding='utf-8'),
        logging.StreamHandler()
    ]
)

logger = logging.getLogger(__name__)

class SensorMonitor:
    def __init__(self, sensor_type=None):
        """
        初始化传感器监测器
        sensor_type: 'serial' 或 'modbus'，如果为None则从配置文件读取
        """
        self.sensor_type = sensor_type or SENSOR_CONFIG.get('type', 'serial')
        self.sensor_handler = SensorHandler(sensor_type=self.sensor_type)
        self.data_manager = DataManager()
        self.server_client = ServerClient()
        self.running = True
        self.reading_interval = SENSOR_CONFIG.get('reading_interval', 5)
        
    def signal_handler(self, signum, frame):
        """处理中断信号"""
        logger.info("接收到停止信号，正在关闭程序...")
        self.running = False
    
    def run_serial_mode(self, ser):
        """运行串口模式"""
        while self.running:
            try:
                if ser.in_waiting > 0:
                    raw_data = ser.readline().decode('utf-8').strip()
                    print(f"原始数据: {raw_data}")
                    
                    # 解析传感器数据
                    parsed_data = self.sensor_handler.parse_sensor_data(raw_data)
                    
                    if parsed_data is not None:
                        self._process_sensor_data(parsed_data)
                
                time.sleep(0.1)
                
            except Exception as e:
                logger.error(f"串口数据处理错误: {e}")
                time.sleep(1)
    
    def run_modbus_mode(self):
        """运行Modbus模式"""
        while self.running:
            try:
                # 读取Modbus传感器数据
                parsed_data = self.sensor_handler.read_modbus_sensors()
                
                if parsed_data is not None:
                    print(f"读取数据: 温度={parsed_data.get('temperature')}°C, "
                          f"湿度={parsed_data.get('humidity')}%, "
                          f"气压={parsed_data.get('pressure')}kPa")
                    
                    self._process_sensor_data(parsed_data)
                else:
                    print("传感器数据读取失败")
                
                time.sleep(self.reading_interval)
                
            except Exception as e:
                logger.error(f"Modbus数据处理错误: {e}")
                time.sleep(1)
    
    def _process_sensor_data(self, parsed_data):
        """处理传感器数据"""
        # 保存数据
        sensor_records = self.data_manager.load_existing_data()
        sensor_records = self.data_manager.save_sensor_data(
            sensor_records, parsed_data
        )
        
        # 检查是否发送到服务器
        if self.server_client.should_send_data(parsed_data):
            logger.info("GPS信号正常，正在发送数据到服务器...")
            send_success = self.server_client.send_data_to_server(parsed_data)
            if send_success:
                print("✓ 数据发送成功")
            else:
                print("✗ 数据发送失败，但已保存到本地")
        else:
            print("⚠ GPS无信号，跳过服务器发送，数据已保存到本地")
    
    def run(self):
        """运行主程序"""
        logger.info("=== 传感器监测系统启动 ===")
        logger.info(f"Version 2.2: 传感器类型={self.sensor_type}")
        
        # 注册信号处理器
        signal.signal(signal.SIGINT, self.signal_handler)
        signal.signal(signal.SIGTERM, self.signal_handler)
        
        # 初始化测量环境
        self.sensor_handler.get_measurement_environment()
        
        try:
            # 连接传感器
            logger.info(f"正在连接{self.sensor_type}传感器...")
            sensor_connection = self.sensor_handler.connect_sensor()
            logger.info("传感器连接成功，开始监测...")
            print("=" * 50)
            print(f"系统运行中（{self.sensor_type}模式），按 Ctrl+C 停止程序")
            print(f"读取间隔: {self.reading_interval}秒" if self.sensor_type == 'modbus' else "实时读取")
            print("=" * 50)
            
            # 根据传感器类型运行不同的监测模式
            if self.sensor_type == 'modbus':
                self.run_modbus_mode()
            else:
                self.run_serial_mode(sensor_connection)
        
        except KeyboardInterrupt:
            logger.info("用户中断程序")
        except Exception as e:
            logger.error(f"程序运行错误: {e}")
        finally:
            # 关闭连接
            if self.sensor_type == 'serial' and 'sensor_connection' in locals():
                if hasattr(sensor_connection, 'is_open') and sensor_connection.is_open:
                    sensor_connection.close()
                    logger.info("串口传感器连接已关闭")
            
            logger.info("程序已退出")

def main():
    """主函数"""
    import sys
    
    # 检查命令行参数确定传感器类型
    sensor_type = None  # 默认从配置文件读取
    
    if len(sys.argv) > 1:
        if sys.argv[1] == '--modbus':
            sensor_type = 'modbus'
        elif sys.argv[1] == '--serial':
            sensor_type = 'serial'
        elif sys.argv[1] == '--help':
            print("使用方法:")
            print("  python main.py           # 使用配置文件中的传感器类型")
            print("  python main.py --modbus  # 强制使用Modbus模式")
            print("  python main.py --serial  # 强制使用串口模式")
            return
    
    # 显示当前配置
    actual_type = sensor_type or SENSOR_CONFIG.get('type', 'serial')
    print(f"启动传感器监测系统 - {actual_type}模式")
    if sensor_type is None:
        print("(从配置文件读取传感器类型)")
    
    monitor = SensorMonitor(sensor_type=sensor_type)
    monitor.run()

if __name__ == "__main__":
    main()
